package com.heima.comment;

import com.heima.apis.ap_user.IApUserClient;
import com.heima.apis.sensitive.ISensitiveClient;
import com.heima.comment.aliyun.GreenTextScan;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.utils.common.CommentUserThreadLocalUtil;
import com.heima.utils.common.SensitiveWordUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author jay
 * @date 2022/11/17 20:46:24
 */
public class ParamCheckUtil {

    public static ApComment isCheckPasted(String content, Long articleId,
                                          IApUserClient apUserClient,
                                          ISensitiveClient sensitiveClient,
                                          GreenTextScan greenTextScan){

        // 检验是否超过140个字
        if(content.length() > 140){
            return null;
        }

        // 1 校验用户是否存在
        ResponseResult result = apUserClient.getUserInfo(CommentUserThreadLocalUtil.get().getId());
        HashMap<String, Object> userInfoMap = (HashMap<String, Object>) result.getData();
        if(userInfoMap.get("id") == null){
            return null;
        }
        // 2 校验评论是否违规
        // 2.1 本地校验
        List<String> sensitiveList = (List<String>)sensitiveClient.getAll().getData();
        SensitiveWordUtil.initMap(sensitiveList);
        Map<String, Integer> matchMap =  SensitiveWordUtil.matchWords(content);
        if(!matchMap.isEmpty()){
            return null;
        }
        // 2.2 阿里云校验
        if(!isAliScanPassed(content, greenTextScan)){
            return null;
        }

        // 3.数据准备
        ApComment comment = new ApComment();
        comment.setAuthorId((Integer) userInfoMap.get("id"));
        comment.setAuthorName((String) userInfoMap.get("name"));
        comment.setImage((String) userInfoMap.get("image"));
        comment.setContent(content);
        comment.setLikes(0);
        comment.setEntryId(articleId);
        comment.setReply(0);
        comment.setFlag(0);
        comment.setCreatedTime(System.currentTimeMillis());
        return comment;
    }


    private static boolean isAliScanPassed(String content, GreenTextScan greenTextScan) {

        boolean flag = true;

        try {
            Map map = greenTextScan.greeTextScan(content);
            if(map != null){
                //审核失败
                if(map.get("suggestion").equals("block")){
                    flag = false;
                }

                //不确定信息  需要人工审核
                if(map.get("suggestion").equals("review")){
                    flag = false;
                }
            }
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }

        return flag;

    }
}
